package com.mall.web.control.app.user;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.mall.biz.user.UserBizImpl;
import com.mall.biz.user.VerifyCodeBizImpl;
import com.mall.client.commkey.CommKeyService;
import com.mall.client.user.UserService;
import com.mall.common.Consts.PassJiaMi;
import com.mall.common.util.MD5Util;
import com.mall.common.util.bit.PropertiesConfigure;
import com.mall.common.util.token.TokenUtils;
import com.mall.constant.PropertiesKey;
import com.mall.enums.EshopErrorTypeEnum;
import com.mall.enums.RegionEnum;
import com.mall.pojo.Commkey;
import com.mall.pojo.User;
import com.mall.pojo.UserExtended;
import com.mall.vo.user.AliTonghua;
import com.mall.vo.user.UserVO;
import com.mall.web.annotation.CheckCommmonOnlyKey;
import com.mall.web.util.AliBaiChuanUtil;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.Log4jUtil;
import com.mall.web.util.WebUtil;
import com.mall.web.vo.ResponseEntity;


@Controller
@RequestMapping("/user/register/")
public class RegisterController {
	private Logger log = LoggerFactory.getLogger(RegisterController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private VerifyCodeBizImpl verifyCodeBiz;
	@Autowired
	private PropertiesConfigure propertiesConfigure;

	@Autowired
	private CommKeyService commKeyService;
	@Autowired
	private UserBizImpl userBiz;
	private final String USERPNG = "user/nan.png";

	/**
	 * 注册
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@CheckCommmonOnlyKey
	@RequestMapping("register")
	public String register(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		modelMap.put("onlyKey", onlyKey);
		return "user/register/register";

	}

	@CheckCommmonOnlyKey
	@RequestMapping("registerAction")
	@ResponseBody
	public ResponseEntity<UserVO> registerAction(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<>();

		String phone = request.getParameter("phone") == null ? "" : request.getParameter("phone").trim();
		String valid = request.getParameter("valid") == null ? "" : request.getParameter("valid").trim();// 验证码

		String deviceToken = request.getParameter("deviceToken");// 手机对应型号
		if (StringUtils.isBlank(phone) || StringUtils.isBlank(valid)) {
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("注册失败");
			return responseEntity;
		}

		User userPhone = this.userService.getUserByPhone(phone, onlyKey);// 校验手机号是否注册过
		if (userPhone != null) {
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("phone and password is error");
			return responseEntity;
		}

		String userName = request.getParameter("userName").trim();
		String passWord = request.getParameter("passWord").trim();
		UserVO userVO = new UserVO();
		Date createTime = new Date();
		User user = new User();
		user.setPassword(getPassWordMd5(passWord, phone));// 注册时密码不需要校验吗？还需要md5加密
		user.setPortrait(USERPNG);
		user.setPhone(phone);
		user.setUserName(phone);
		user.setNameAndPhone(phone + phone);
		/**
		 * 根据onlykey存对应的省市区
		 */
		List<Commkey> commKeyList = this.commKeyService.getComKeyByCommOnlyKey(onlyKey);
		user.setCommOnlyKey(onlyKey);
		user.setProvinceId(commKeyService.getRegionByList(RegionEnum.PROVINCE.getCode(), commKeyList));
		user.setCityId(commKeyService.getRegionByList(RegionEnum.CITY.getCode(), commKeyList));
		user.setAreaId(commKeyService.getRegionByList(RegionEnum.AREA.getCode(), commKeyList));
		userVO.setUser(user);

		/**
		 * 用户阿里百川存入数据库
		 */
		String aliUserId = AliBaiChuanUtil.UID + phone;
		String aliPass = AliBaiChuanUtil.PASS;
		AliTonghua aliTonghua = new AliTonghua(aliUserId, aliPass);
		UserExtended userExtended = new UserExtended();
		userExtended.setAliTongxun(JSONArray.toJSONString(aliTonghua));
		userExtended.setAliTongxueId(aliUserId);
		userExtended.setDeviceToken(deviceToken);
		userVO.setUserExtended(userExtended);
		this.userService.register(userVO, createTime);
		/**
		 * 用户注册到阿里百川
		 */
		boolean insertResult = AliBaiChuanUtil.insertUserInfoAliBaiChuan(user);
		log.error("插入用户到阿里百川" + insertResult);

		Boolean sessResult = userBiz.updateOrInsertSess(request, response, userVO, onlyKey);
		log.info("更新session", sessResult);
		if (!sessResult) {
			responseEntity.setCode("-500");
			responseEntity.setData(null);
			responseEntity.setMessage("sess insert or update error");
			return responseEntity;
		}

		String userImgUrl = propertiesConfigure.getProperties(PropertiesKey.userfilepath);
		userVO.setImgBeiginUrl(userImgUrl);
		String token = TokenUtils.getToken(userVO.getUser().getId(), user.getPassword(), new Date());
		userVO.setToken(token);
		userVO.setSessionID(WebUtil.getUserCookieValue(request));

		responseEntity.initSuccResponseEntity(userVO, "注册成功");

		return responseEntity;

	}

	@CheckCommmonOnlyKey
	@RequestMapping("forgotPass")
	public String forgotPass(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		return "user/register/forgotPass";

	}

	@CheckCommmonOnlyKey
	@RequestMapping("forgotPassAction")
	@ResponseBody
	public ResponseEntity<UserVO> forgotPassAction(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<>();
		String phone = request.getParameter("phone") == null ? "" : request.getParameter("phone").trim();
		// 如果条件表达式为真，则执前面行程序块1，否则执行后面表达式2的值。Java只有问号表达式，而没有句号表达式
		String valid = request.getParameter("valid") == null ? "" : request.getParameter("valid").trim();// 邀请码
		if (StringUtils.isBlank(phone) || StringUtils.isBlank(valid)) {
			responseEntity.initErrorResponseEntity(null, "phone or volid is null");
		}

		User user = this.userService.getUserByPhone(phone, onlyKey);
		if (user == null) {// 用户不存在，提醒去注册
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("phone and password is error");
			return responseEntity;
		}
		boolean verifyCode = verifyCodeBiz.checkVerifyCode(phone, valid);
		if (verifyCode == false) {
			responseEntity.setCode("-400");
			responseEntity.setData(null);
			responseEntity.setMessage("输入的邀请码错误");
			return responseEntity;
		}

		String passWord = request.getParameter("passWord");
		passWord = passWord.trim();
		user.setGmtModify(new Date());
		
		user.setPassword(getPassWordMd5(passWord, user.getPhone()));// 忘记密码时候设置新密码
		this.userService.modifytUserByPrimaryKey(user);
		UserVO userVO = new UserVO();
		userVO.setUser(user);
		Boolean sessResult = this.userBiz.updateOrInsertSess(request, response, userVO, onlyKey);
		log.info("更新session", sessResult);

		responseEntity.initSuccResponseEntity(userVO, "set pass success");
		return responseEntity;

	}

	private String getPassWordMd5(String passWord, String phone) {
		return MD5Util.GetMD5Code(passWord, phone + "", PassJiaMi.MD5JIAYAN);
	}
	
	/**
	 * 检测手机号是否注册过
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@CheckCommmonOnlyKey
	@RequestMapping("checkPhone")
	@ResponseBody
	public ResponseEntity<UserVO> checkPhone(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		String phone = request.getParameter("phone");
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<>();
		User user = this.userService.getUserByPhone(phone, onlyKey);
		if (user != null) {
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("phone and is error");
			return responseEntity;
		}
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("phone can use");
		return responseEntity;
	}
	
	/**
	 * 检测用户名是否注册过
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@CheckCommmonOnlyKey
	@RequestMapping("checkUserName")
	@ResponseBody
	public ResponseEntity<UserVO> checkUsername(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		String userName = request.getParameter("userName");
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<>();
		User user = this.userService.getUserByUserName(userName, onlyKey);
		if (user != null) {
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("username is using");
			return responseEntity;
		}
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("username can use");
		return responseEntity;
	}
	
	/**
	 * 注册表单提交
	 * @param request
	 * @param response
	 * @param modelMap
	 * @param user
	 * @return
	 */
	@RequestMapping(value="pcRegisterAction",method=RequestMethod.POST)
	public String pcRegisterAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		User user = new User();
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		String qq = HttpUtil.getStringValueFromRequest(request, "qq");
		String email = HttpUtil.getStringValueFromRequest(request, "email");
		String password = HttpUtil.getStringValueFromRequest(request, "password").trim();
		String userName = HttpUtil.getStringValueFromRequest(request, "userName");
		String phone = HttpUtil.getStringValueFromRequest(request, "phone");
		String valid = HttpUtil.getStringValueFromRequest(request, "dxmessage");
		boolean verifyCode = verifyCodeBiz.checkVerifyCode(phone, valid);
		if(!verifyCode){
			return "redirect:/eshop/pcEshopRegister.htm";
		}
		
		Date date = new Date();
		user.setPassword(getPassWordMd5(password, phone));// 注册时密码不需要校验吗？还需要md5加密
		user.setPortrait(USERPNG);
		user.setPhone(phone);
		user.setGmtCreate(date);
		user.setGmtModify(date);
		user.setUserName(userName);
		user.setNameAndPhone(userName + phone);
		
		/**
		 * 根据onlykey存对应的省市区
		 */
		List<Commkey> commKeyList = this.commKeyService.getComKeyByCommOnlyKey(onlyKey);
		user.setCommOnlyKey(onlyKey);
		user.setProvinceId(commKeyService.getRegionByList(RegionEnum.PROVINCE.getCode(), commKeyList));
		user.setCityId(commKeyService.getRegionByList(RegionEnum.CITY.getCode(), commKeyList));
		user.setAreaId(commKeyService.getRegionByList(RegionEnum.AREA.getCode(), commKeyList));
		
		UserVO userVO = new UserVO();
		if(StringUtils.isNotBlank(qq) || StringUtils.isNotBlank(email)){
			Map<String ,String> map = new HashMap<>();
			map.put("qq", qq);
			map.put("email", email);
			JSONArray jsonArray = new JSONArray();
			jsonArray.add(map);
			user.setAttribute(jsonArray.toJSONString());
		}
		userVO.setUser(user);
		String deviceToken = request.getParameter("deviceToken");// 手机对应型号
		
		/**
		 * 用户阿里百川存入数据库
		 */
		String aliUserId = AliBaiChuanUtil.UID + phone;
		String aliPass = AliBaiChuanUtil.PASS;
		AliTonghua aliTonghua = new AliTonghua(aliUserId, aliPass);
		UserExtended userExtended = new UserExtended();
		userExtended.setAliTongxun(JSONArray.toJSONString(aliTonghua));
		userExtended.setAliTongxueId(aliUserId);
		userExtended.setDeviceToken(deviceToken);
		userVO.setUserExtended(userExtended);
		Integer result = this.userService.register(userVO, date);
		/**
		 * 用户注册到阿里百川
		 */
		boolean insertResult = AliBaiChuanUtil.insertUserInfoAliBaiChuan(user);
		log.error("插入用户到阿里百川" + insertResult);

		Boolean sessResult = this.userBiz.updateOrInsertSess(request, response, userVO, onlyKey);
		log.info("更新session", sessResult);
		if(result<=0 || result == null ||sessResult == false ){
			Log4jUtil.printLog(EshopErrorTypeEnum.REGISTERERROR.getDesc(), phone);
		}
		return "redirect:/eshop/pcindex.htm";
		
	}
	
}
